/** 
 * Copyright(C) 2010-2011 <webPrj> LTD. All Rights Reserved.                               
 * Project: webPrj
 * Module ID: <0001>
 * Comments: TODO         
 * JDK version used: <JDK1.6.0_25>                              
 * Author: xiamingxing
 * Create Date：10:30:01
 * Modified By: xiamingxing                              
 * Modified Date: 10:30:01                                  
 * Why & What is modified: <修改原因描述>    
 * Version: V1.0                  
 */
package com.xiamx.platform.util;

import java.awt.image.BufferedImage;
import java.io.BufferedInputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.RandomAccessFile;
import java.net.SocketException;
import java.net.URL;
import java.text.ParseException;

import javax.imageio.ImageIO;

import org.apache.commons.codec.binary.Base64;
import org.apache.commons.net.ftp.FTPClient;

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import com.xiamx.platform.constants.sys.SysConst;

public class FtpUtil {

	private FTPClient ftpClient;
	private String fileName, strencoding;
	private String readIp = FileUtil.getResource(SysConst.SYS_PROPERTIES_PATH, SysConst.FTP_READ_IP); //服务器IP地址
	private String readUserName = FileUtil.getResource(SysConst.SYS_PROPERTIES_PATH, SysConst.FTP_READ_USERNAME); //用户名
	private String readUserPwd = FileUtil.getResource(SysConst.SYS_PROPERTIES_PATH, SysConst.FTP_READ_PASSWORD); //密码
	private int readPort = Integer.parseInt(FileUtil.getResource(SysConst.SYS_PROPERTIES_PATH, SysConst.FTP_READ_PORT)); //服务器端口号
	private String readPath = ""; //读取文件的存放目录
	
	private String uploadFileName;
	private String uploadIp = FileUtil.getResource(SysConst.SYS_PROPERTIES_PATH, SysConst.FTP_UPLOAD_IP); //服务器IP地址
	private String uploadUserName = FileUtil.getResource(SysConst.SYS_PROPERTIES_PATH, SysConst.FTP_UPLOAD_USERNAME); //用户名
	private String uploadUserPwd = FileUtil.getResource(SysConst.SYS_PROPERTIES_PATH, SysConst.FTP_UPLOAD_PASSWORD); //密码
	private int uploadPort = Integer.parseInt(FileUtil.getResource(SysConst.SYS_PROPERTIES_PATH, SysConst.FTP_UPLOAD_PORT)); //服务器端口号
	private String uploadDir = FileUtil.getResource(SysConst.SYS_PROPERTIES_PATH, SysConst.FTP_V_UPLOAD_DIR); //服务器端口号
	private String uploadPath = ""; //读取文件的存放目录
	
	/**
	 * init ftp servere
	 */
	public FtpUtil(String ImagePath) {
		strencoding = "GBK";
		String ImagePathStr = StringUtil.decodeStr(ImagePath, strencoding);
		
		String[] pathStr = ImagePathStr.split("/");
		
		//获取读取图片的存放目录
		for(int i = 3; i < pathStr.length-1; i++){
			readPath += pathStr[i];
			readPath += "/";
		}
		
		//获取读取图片的文件名
		fileName = pathStr[pathStr.length-1];
		//连接到服务器
		this.connectServer(readIp, readPort, readUserName, readUserPwd, readPath); 
	}
	
	public FtpUtil(String ImagePath,String flag){
		strencoding = "GBK";
		String ImagePathStr = StringUtil.decodeStr(ImagePath, strencoding);
		if("des".equalsIgnoreCase(flag)) {
			String[] pathStr = ImagePathStr.split("/");
			//获取文件的存放目录
			for(int i = 0; i < pathStr.length-1; i++){
				uploadPath += pathStr[i];
				uploadPath += "/";
			}
			uploadPath = uploadDir + uploadPath;
			//获取文件的文件名
			uploadFileName = pathStr[pathStr.length-1];
			//连接到服务器
			this.connectServer(uploadIp, uploadPort, uploadUserName, uploadUserPwd, uploadPath); 
			
		}
	}

	/**
	 * @param ip
	 * @param port
	 * @param userName
	 * @param userPwd
	 * @param path
	 * @throws SocketException
	 * @throws IOException
	 * function:连接到服务器
	 */
	public void connectServer(String ip , int port , String userName , String userPwd , String path){
		ftpClient = new FTPClient();
		try {
			// 连接
			ftpClient.connect(ip, port);
			// 登录
			ftpClient.login(userName, userPwd);
		} catch (SocketException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	/**
	 * @throws IOException
	 * function:关闭连接
	 */
	public void closeServer(){
		if(ftpClient.isConnected()){
			try {
				ftpClient.logout();
				ftpClient.disconnect();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}


	/**
	 * @param fileName
	 * @return
	 * function:从服务器上读取指定的文件
	 * @throws ParseException 
	 * @throws IOException 
	 */
	public String readFile() {

		byte[] data = null; // 读取图片字节数组 
		InputStream ins = null;
		BufferedImage bi;  
		try {
			if(readPath != null && readPath.length() > 0){
				String filePath = new String(readPath.getBytes(strencoding),"iso-8859-1");
				// 跳转到指定目录
				ftpClient.changeWorkingDirectory(filePath);
				
			}
			
			//从服务器上读取指定的文件
			ins = ftpClient.retrieveFileStream(fileName);
			bi = ImageIO.read(ins);
			
			ByteArrayOutputStream baos = new ByteArrayOutputStream();  
            ImageIO.write(bi, "jpg", baos); 
            
            data = baos.toByteArray();

			if(ins != null){
				ins.close(); 
			}
			
			ftpClient.getReply();
			closeServer();
		} catch (IOException e) {
			System.out.println("FtpUtil.java从服务器上读取图片出错！");
			e.printStackTrace();
		}
		
		BASE64Encoder encoder = new sun.misc.BASE64Encoder();
		// 返回Base64编码过的字节数组字符串
		return encoder.encode(data);
	}
	
	/**
	 * 将图片进行base64编码
	 * @return
	 */
	public String readImgToBase64() {
		
		byte[] data = null; // 读取图片字节数组 
		InputStream ins = null;
		BufferedImage bi;  
		try {
			if(readPath != null && readPath.length() > 0){
				String filePath = new String(readPath.getBytes(strencoding),"iso-8859-1");
				// 跳转到指定目录
				ftpClient.changeWorkingDirectory(filePath);
				
			}
			
			//从服务器上读取指定的文件
			ins = ftpClient.retrieveFileStream(fileName);
			if(ins != null){
				bi = ImageIO.read(ins);
				ByteArrayOutputStream baos = new ByteArrayOutputStream();  
				ImageIO.write(bi, "jpg", baos); 
				data = baos.toByteArray();
			}
			
		} catch (IOException e) {
			System.out.println("FtpUtil.java从服务器上读取图片出错！");
			e.printStackTrace();
		} finally {
			if(ins != null){
				try {
					ins.close();
				} catch (IOException e) {
					e.printStackTrace();
				} 
			}
			closeServer();
		}
		Base64 encoder = new Base64();
		return encoder.encodeToString(data);
	}
	
	/**
	 * 
	 * @description ：从FTP服务器中读取图片转换成字节数组
	 * @param  ：
	 * @return : byte[]
	 * @throw  : 
	 * @author : xiamx
	 */
	@SuppressWarnings("unused")
	public byte[] readFileFromFtp(){
		byte[] data = null; // 读取图片字节数组 
		InputStream ins = null;
		BufferedImage bi;  
		try {
			if(readPath != null && readPath.length() > 0){
				String filePath = new String(readPath.getBytes(strencoding),"iso-8859-1");
				// 跳转到指定目录
				boolean falg = ftpClient.changeWorkingDirectory(filePath);
//				System.out.println(falg);
			}
			
			//从服务器上读取指定的文件
			ins = ftpClient.retrieveFileStream(fileName);
			bi = ImageIO.read(ins);
			
			ByteArrayOutputStream baos = new ByteArrayOutputStream();  
            ImageIO.write(bi, "jpg", baos);  
            
            data = baos.toByteArray();

			if(ins != null){
				ins.close(); 
			}
			
			ftpClient.getReply();
			closeServer();
		} catch (IOException e) {
			System.out.println("FtpUtil.java从服务器上读取图片出错！");
			e.printStackTrace();
		}
		return data;
	}
	
	@SuppressWarnings("unused")
	public String downloadFileFromFtp() {
		String tempfilePath = null;
		InputStream ins = null;
		File newFile = null;
		RandomAccessFile readFile = null; 
		int ch;
		try {
			if(readPath != null && readPath.length() > 0){
				String filePath = new String(readPath.getBytes(strencoding),"iso-8859-1");
				// 跳转到指定目录
				boolean falg = ftpClient.changeWorkingDirectory(filePath);
				//System.out.println(falg);
			}
			//从服务器上读取指定的文件
			ins = ftpClient.retrieveFileStream(fileName);
			URL serverUrl = FtpUtil.class.getResource("/");
			String serverRoot = serverUrl.getPath();
			String tempImgPath = serverRoot + "downloadimg";
			if(!new File(tempImgPath).isDirectory()) {
				new File(tempImgPath).mkdirs();
			}
			newFile = new File(tempImgPath + "/" + fileName);
			DataInputStream puts = new DataInputStream(ins);//           
            readFile = new RandomAccessFile(newFile,"rw");//以读写的方式打开本地文件  
            readFile.seek(0); //将指针放到文件最前段  
            while ((ch = puts.read()) >= 0) {//循环读取远程文件的内容并写入本地文件中  
            	readFile.write(ch);  
            }
			ftpClient.getReply();
			tempfilePath = tempImgPath + "/" + fileName;
		} catch (IOException e) {
			tempfilePath = null;
			e.printStackTrace();
		} finally {
			if(ins != null){
				try {
					ins.close();
				} catch (IOException e) {
					tempfilePath = null;
					e.printStackTrace();
				} 
			}
			if(readFile != null) {
				try {
					readFile.close();
				} catch (IOException e) {
					tempfilePath = null;
					e.printStackTrace();
				}
			}
			closeServer();
		}
		return tempfilePath;
	}
	
//	
//	public static void base64StringToImage(String base64String){  
//        try {  
//        	BASE64Decoder decoder = new sun.misc.BASE64Decoder(); 
//            byte[] bytes = decoder.decodeBuffer(base64String);  
//              
//            ByteArrayInputStream bais = new ByteArrayInputStream(bytes);  
//            BufferedImage bi = ImageIO.read(bais);  
//            File w2 = new File("d://test.jpg");//可以是jpg,png,gif格式  
//            ImageIO.write(bi, "jpg", w2);//不管输出什么格式图片，此处不需改动  
//        } catch (IOException e) {  
//            e.printStackTrace();  
//        }  
//    }
	
	/**
	 * 上传文件到指定的目录下
	 *
	 * @param client	被指定上传的目录
	 * @param file		被上传的文件
	 * @throws IOException
	 * @throws FTPAbortedException
	 * @throws FTPDataTransferException
	 * @throws FTPException
	 * @throws FTPIllegalReplyException
	 * @throws IllegalStateException
	*/
	@SuppressWarnings("static-access")
	public void upload(String base64String) {
        ByteArrayInputStream bais = null;
		try{
			BASE64Decoder decoder = new sun.misc.BASE64Decoder(); 
	        byte[] bytes = decoder.decodeBuffer(base64String);
			
			bais = new ByteArrayInputStream(bytes); 
			BufferedInputStream buffIn = new BufferedInputStream(bais);
         
			ftpClient.setFileType(ftpClient.BINARY_FILE_TYPE);
			
			ftpClient.changeWorkingDirectory(readPath);
			boolean uploadFlag = ftpClient.storeFile(fileName, buffIn);
            
			if(uploadFlag) {
				System.out.println("FtpUtil.java_upload数据上传成功！");
			} else {
				System.out.println("FtpUtil.java_upload数据上传失败！");
			}
			
			buffIn.close();
               
        }catch(Exception ex){
            ex.printStackTrace();
            
        }finally{
            
        }
	}
	
	/**
	 * 上传文件到指定的目录下
	 *
	 * @param bytes		被上传的文件
	 * @throws IOException
	 * @throws FTPAbortedException
	 * @throws FTPDataTransferException
	 * @throws FTPException
	 * @throws FTPIllegalReplyException
	 * @throws IllegalStateException
	 */
	@SuppressWarnings("static-access")
	public void upload(byte[] bytes) {
		ByteArrayInputStream bais = null;
		try{
			bais = new ByteArrayInputStream(bytes); 
			BufferedInputStream buffIn = new BufferedInputStream(bais);
			
			ftpClient.setFileType(ftpClient.BINARY_FILE_TYPE);
			
			//如果目录不存在，创建目录
			String filePath = new String(readPath.getBytes(strencoding),"iso-8859-1");
			String[] dirArray = filePath.split("/"); 
			if ( dirArray.length > 1 ) { 
				for ( int i = 0; i < dirArray.length; i++ ) { 
					if ( dirArray[i] != null && dirArray[i] != null ) 
						if ( !ftpClient.changeWorkingDirectory( dirArray[i] ) ) { 
							ftpClient.makeDirectory( dirArray[i] ); 
							ftpClient.changeWorkingDirectory( dirArray[i] ); 
						} 
				} 
			}
			
			boolean uploadFlag = ftpClient.storeFile(fileName, buffIn);
			
			if(uploadFlag) {
				System.out.println("FtpUtil.java_upload数据上传成功！");
			} else {
				System.out.println("FtpUtil.java_upload数据上传失败！");
			}
			
			buffIn.close();
			
		}catch(Exception ex){
			ex.printStackTrace();
			
		}finally{
			
		}
	}
	
	@SuppressWarnings("static-access")
	public boolean uploadFileToFtp(byte [] srcData){
		boolean uploadFlag = false;
		ByteArrayInputStream bais = null;
		BufferedInputStream buffIn = null;
		try{
			bais = new ByteArrayInputStream(srcData); 
			buffIn = new BufferedInputStream(bais);
			ftpClient.setFileType(ftpClient.BINARY_FILE_TYPE);
			//如果目录不存在，创建目录
			String filePath = new String(uploadPath.getBytes(strencoding),"iso-8859-1");
			String[] dirArray = filePath.split("/"); 
			if ( dirArray.length > 1 ) { 
				for ( int i = 0; i < dirArray.length; i++ ) { 
					if ( dirArray[i] != null && dirArray[i] != null ) 
						if ( !ftpClient.changeWorkingDirectory( dirArray[i] ) ) { 
							ftpClient.makeDirectory( dirArray[i] ); 
							ftpClient.changeWorkingDirectory( dirArray[i] ); 
						} 
				} 
			}
			uploadFlag = ftpClient.storeFile(uploadFileName, buffIn);
        }catch(Exception ex){
            ex.printStackTrace();
        }finally{
        	if (null != buffIn) {
        		try {
					buffIn.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
        	}
        }
		return uploadFlag;
	}
	
	public static void main(String[] args) {
	}

}

